<template>
    <div class="container">
        <div class="header">
            <h1>Stable Diffusion模型</h1>
        </div>
        <div class="button-group">
            <button class="model-version-btn">model-version1</button>
            <div class="rectangle-box">文生图</div>
        </div>
        <div class="large-rectangle">
            <div class="small-rectangle top-small-rectangle" contenteditable="true" @input="updateText"
                @focus="placeholderVisible = false" @blur="updatePlaceholderVisibility">
                <span v-if="placeholderVisible" class="placeholder">输入提示词</span>
                <span>{{ editableText }}</span> <!--显示输入的文本 -->
            </div>
            <div class="small-rectangle bottom-small-rectangle">
                <label for="height-slider">高度</label>
                <input type="range" id="height-slider" min="32" max="1024" value="288" @input="updateHeight">
                <div>
                    <button>{{ heightValue }}</button> <!-- 显示高度的按钮 -->
                </div>
                <label for="width-slider">宽度</label>
                <input type="range" id="width-slider" min="32" max="1024" value="512" @input="updateWidth">
                <div>
                    <button>{{ widthValue }}</button> <!-- 显示宽度的按钮 -->
                </div>
                <label for="quantity-slider">生成数量</label>
                <input type="range" id="quantity-slider" min="1" max="100" value="1" @input="updateQuantity">
                <div>
                    <button>{{ quantityValue }}</button> <!-- 显示生成数量的按钮 -->
                </div>
                <div class="start-button-container">
                    <button class="start-button" @click="startGeneration">开始生成</button>
                </div>
            </div>

            <div class="common-terms">
                <h3>常用词条</h3>
                <hr />
                <div class="button-container">
                    <button class="term-btn" @click="insertTerm('词条1')">词条1</button>
                    <span>{{ count1 }}</span>
                </div>
                <div class="button-container">
                    <button class="term-btn" @click="insertTerm('词条2')">词条2</button>
                    <span>{{ count2 }}</span>
                </div>
                <div class="button-container">
                    <button class="term-btn" @click="insertTerm('词条3')">词条3</button>
                    <span>{{ count3 }}</span>
                </div>
            </div>

            <div class="upload-section">
                <el-image :src=imgUrl alt="Uploaded Image" class="uploaded-image" v-loading="loading"/>
                <div class="button-row">
                    <div class="upload-button" @click="handleSave">
                        <img src="@/assets/save.png" alt="Image 1" class="uploaded-image" />
                    </div>
                    <div class="upload-button">
                        <img src="@/assets/pictopic.png" alt="Image 2" class="uploaded-image" />
                    </div>
                    <div class="upload-button" @click="handleEdit">
                        <img src="@/assets/edit.png" alt="Image 3" class="uploaded-image" />
                    </div>
                    <div class="upload-button" @click="handleShare">
                        <img src="@/assets/share.png" alt="Image 4" class="uploaded-image" />
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { ElNotification } from 'element-plus';
import { useRouter } from 'vue-router';

export default {
    name: 'StableDiffusionInterface',
    data() {
        return {
            router: useRouter(),
            heightValue: 288,
            widthValue: 512,
            quantityValue: 1,
            count1: 0,
            count2: 0,
            count3: 0,
            editableText: '',
            transText: '',
            placeholderVisible: true, // 初始值为 true，提示词可见
            imgUrl: '/src/assets/image3.jpg',
            loading: false
        };
    },
    methods: {
        updateHeight(event) {
            this.heightValue = event.target.value;
        },
        updateWidth(event) {
            this.widthValue = event.target.value;
        },
        updateQuantity(event) {
            this.quantityValue = event.target.value;
        },
        updateText(event) {
            this.editableText = event.target.innerText; // 使用 innerText 获取内容
        },
        insertTerm(term) {
            this.editableText += term; // 在现有文本后添加词条
            this.placeholderVisible = false; // 插入后隐藏提示词
        },
        clearPlaceholder() {
            if (this.editableText === '') {
                this.editableText = ''; // 清空内容
            }
        },
        setPlaceholder() {
            if (this.editableText === '') {
                this.editableText = ''; // 保持为空
            }
        },
        handleFileUpload(event) {
            const file = event.target.files[0];
            if (file) {
                this.uploadedImage = URL.createObjectURL(file);
            }
        },
        async translate() {
            const url = 'http://localhost:8080/api/image/translate';
            try {
                const response = await fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'text/plain'
                    },
                    body: JSON.stringify({
                        text: this.editableText
                    })
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status}`);
                }

                const text = await response.text();
                this.transText = text; // 将翻译结果存储到 transText
                console.log('Translation completed:', this.transText);
            } catch (error) {
                console.error('Error in translate:', error);
            }
        },
        async getImg() {
            try {
                const imgResponse = await fetch('http://172.29.41.219:8989/sd1', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'text/plain'
                    },
                    body: JSON.stringify({
                        text: this.transText,
                        token: "7tPFTSO8oSfu3V2k",
                        width: this.widthValue,
                        height: this.heightValue
                    })
                });
                if (!imgResponse.ok) {
                    throw new Error(`HTTP error! Status: ${imgResponse.status}`);
                }
                const imageUrl = await imgResponse.text();
                this.imgUrl = imageUrl;
                console.log(this.imgUrl);
            } catch (error) {
                console.error('Error in getImg:', error);
                throw error; // 继续抛出错误，确保后续不会执行
            }
        },

        async saveGeneration() {
            const url = 'http://localhost:8080/api/image/insertImage'
            try {
                console.log("save: " + this.imgUrl);
                // 这里可以添加具体的保存逻辑
                const response = await fetch(url, {
                    method: 'POST',
                    credentials: 'include',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify({
                        width: this.widthValue,
                        height: this.heightValue,
                        imageUrl: this.imgUrl,
                        description: this.editableText,
                        type: 0
                    })
                });
                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status}`);
                }
                const data = await response.json()

                if (data['code'] == 200) {
                    ElNotification({
                        title: 'Success',
                        message: '生成记录保存成功',
                        type: 'success'
                    })
                } else {
                    ElNotification({
                        title: 'Error',
                        message: '生成记录保存失败',
                        type: 'error',
                    })
                }
            } catch (error) {
                console.error('Error in saveGeneration:', error);
            }
        },
        async startGeneration() {
            this.loading = true;
            console.log("开始生成，当前设置：", {
                height: this.heightValue,
                width: this.widthValue,
                quantity: this.quantityValue,
                text: this.editableText
            });
            await this.translate()
            // 这里可以添加具体的生成逻辑
            console.log(this.transText)
            await this.getImg()
            await this.saveGeneration()
            this.loading = false;
        },
        handleEdit() {
            localStorage.setItem('imgUrl', this.imgUrl)
            this.$router.push('/second_editing')
        },
        handleSave() {
            const link = document.createElement("a");
            link.href = this.imgUrl;
            link.download = 'image.png'
            link.click();
            document.removeChild(link);
        },
        async handleShare() {
            try {
                await navigator.clipboard.writeText(this.imgUrl);
                ElNotification({
                    title: 'URL以复制到剪切板',
                    message: this.imgUrl,
                    type: 'success'
                })
            } catch (err) {
                ElNotification({
                    title: 'Error',
                    message: 'URL复制失败',
                    type: 'error'
                })
            }
        }
    }
}
</script>

<style>
body {
    background-color: #faecd7;
}

.container {
    width: 100%;
    height: 100%;
    /* 确保容器至少等于视口高度 */
    padding: 20px;
    /* 添加内边距以避免内容紧贴边缘 */
    font-family: Arial, sans-serif;
    margin: 0;
    background-color: #faecd7;
}

.header h1 {
    font-size: 16px;
    margin: 0;
}

.button-group {
    position: relative;
    margin-top: -5px;
}

.model-version-btn {
    background-color: #fefcf9;
    color: black;
    border: none;
    padding: 10px 50px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 10px;
    border-radius: 15px;
    cursor: pointer;
}

.arrow-btn {
    background-color: #ffffff;
    color: black;
    border: none;
    padding: 15px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 20px;
    border-radius: 50%;
    position: absolute;
    bottom: -60px;
    left: 30px;
    cursor: pointer;
}

.rectangle-box {
    background-color: #f1f1f1;
    color: black;
    padding: 15px 50px;
    display: inline-block;
    font-size: 20px;
    font-weight: bold;
    border-radius: 5px;
    margin-left: -148px;
    position: relative;
    bottom: -60px;
}

.large-rectangle {
    background-color: #f0f0f0;
    height: 80%;
    width: 95%;
    margin-top: 60px;
    margin-left: 20px;
    margin-right: auto;
    display: flex;
    /* 使用 Flexbox 布局 */
    flex-direction: column;
    /* 垂直排列子元素 */
    justify-content: flex-end;
    /* 将子元素放置在底部 */
    align-items: flex-end;
    /* 将子元素放置在右侧 */
    position: relative;
    /* 为内部绝对定位的元素提供定位上下文 */
}

.small-rectangle {
    background-color: #ffffff;
    /* 小矩形的背景颜色 */
    border-radius: 5px;
    /* 边框圆角 */
    padding: 10px;
    /* 内边距 */
    position: absolute;
    /* 绝对定位 */
}

.top-small-rectangle {
    display: flex;
    height: 28%;
    /* 上方小矩形的高度 */
    width: 38.7%;
    /* 上方小矩形的宽度 */
    top: 5%;
    /* 添加底部间距 */
    left: 5%;
    padding: 10px;
    /* 内边距 */
    border: 1px solid #ccc;
    /* 边框 */
    background-color: #ffffff;
    /* 背景颜色 */
    border-radius: 5px;
    /* 圆角 */
    overflow: auto;
    /* 超出部分可滚动 */
}

.placeholder {
    color: #999;
    /* 提示词颜色 */
    position: absolute;
    /* 绝对定位 */
    pointer-events: none;
    /* 不阻止鼠标事件 */
}

.bottom-small-rectangle {
    display: flex;
    width: 38.7%;
    height: 48%;
    display: flex;
    flex-direction: column;

    margin-top: 10px;
    /* 可以调整 */
    bottom: 5%;
    /* 将底部间距设置为 0 */
    left: 5%;
    /* 将左侧间距设置为 0 */
    margin-right: 0;
    /* 可能需要设置右侧间距以对齐 */
}

.start-button-container {
    width: 40%;
    height: 20%;
    position: absolute;
    /* 确保容器能够定位 */
    bottom: 5%;
    /* 距底部的距离 */
    right: 5%;
    /* 距右边的距离 */
}

.start-button {
    background-color: #db5824;
    /* 按钮背景颜色 */
    color: white;
    /* 字体颜色 */
    border: none;
    /* 去掉边框 */
    padding: 0;
    /* 去掉内边距，以便按钮完全充满容器 */
    border-radius: 5px;
    /* 圆角 */
    cursor: pointer;
    /* 鼠标悬停时为手型 */
    width: 100%;
    /* 让按钮宽度充满容器 */
    height: 100%;
    /* 让按钮高度充满容器 */
    box-sizing: border-box;
    /* 包含边框和内边距 */
}

.start-button:hover {
    background-color: #45a049;
    /* 悬停时的背景颜色 */
}

.common-terms {
    position: absolute;
    background-color: #ffffff;
    /* 常用词条小矩形的背景颜色 */
    border-radius: 5px;
    /* 边框圆角 */
    /* 离大矩形顶部的距离 */
    top: 5%;
    right: 4%;
    /* 离大矩形右边的距离 */
    padding: 10px;
    height: 28%;
    width: 43.7%;
}

.common-terms h3 {
    margin: 0;
    /* 去除默认的 margin */
    font-size: 14px;
    /* 标题字体大小 */
}

hr {
    border: 0;
    height: 1px;
    background: #ccc;
    /* 分隔线颜色 */
    margin: 5px 0;
    /* 分隔线的上下间距 */
}

.button-container {
    display: flex;
    /* 设置为 flexbox 布局 */
    justify-content: space-between;
    /* 按钮和计数之间的间隔 */
    align-items: center;
    /* 垂直居中对齐 */
    margin-bottom: 5px;
    /* 每个按钮容器之间的间距 */
}

.term-btn {
    background-color: #f1f1f1;
    /* 按钮背景颜色 */
    border: none;
    /* 去除边框 */
    border-radius: 15px;
    /* 按钮圆角 */
    padding: 5px 10px;
    /* 按钮内边距 */
    cursor: pointer;
    /* 鼠标悬停时为手型 */
    width: 25%;
}

label {
    display: block;
    /* 标签块状显示 */
    margin: 5px 0;
    /* 上下间距 */
}

input[type="range"] {
    width: 50%;
    /* 滑动条宽度 */
}

input[type="file"] {
    margin-top: 10px;
    /* 文件输入框的上间距 */
}

.upload-section {
    background-color: #f6f4ef;
    border-radius: 5px;
    padding: 10px;
    width: 43.7%;
    height: 48%;
    /* 让高度根据内容自适应 */
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 3%;
    margin-right: 4%;
}

.uploaded-image {
    display: block;
    /* 将图片设为块级元素 */
    max-width: 85%;
    /* 最大宽度为父容器的85% */
    max-height: 85%;
    /* 最大高度为父容器的75% */
    width: auto;
    /* 宽度自适应 */
    height: auto;
    /* 高度自适应 */
    margin: 0;
    /* 确保没有额外的间距 */
}


.button-row {
    margin-bottom: 0px;
    display: flex;
    justify-content: space-between;
    /* 等间距排列按钮 */
    width: 100%;
    max-width: 70%;
    /* 限制按钮行的最大宽度 */
    margin-top: 10px;
    /* 图片与按钮之间的间距 */
}

.upload-button {
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 5px 0;
    /* 按钮之间的垂直间距 */
    width: 22%;
    /* 调整按钮宽度，使四个按钮总宽度适应 */
    max-width: 50px;
    /* 设置每个按钮的最大宽度 */
    padding: 5px;
    /* 调整按钮内边距 */
    border-radius: 20px;
    /* 圆角 */
    background-color: #ffffff;
    /* 按钮背景颜色 */
    transition: background-color 0.3s, transform 0.3s;
    /* 添加过渡效果 */
    cursor: pointer;
    /* 鼠标悬停时为手型 */
}

.upload-button img {
    max-width: 80%;
    /* 调整图片宽度 */
    height: auto;
    /* 高度自适应 */
}

.upload-button:hover {
    background-color: #f0f0f0;
    /* 悬停时背景颜色 */
    transform: scale(1.05);
    /* 悬停时放大效果 */
}


.action-btn:hover {
    background-color: #e0e0e0;
    /* 悬停效果 */
}

.arrow-btn:hover,
.rectangle-box:hover {
    background-color: #f0f0f0;
    /* 悬停效果 */
}

@media (max-width: 768px) {
    .container {
        padding: 10px;
        /* 小屏幕内边距 */
    }
}
</style>